<template>
  <div>
    <my-breadcrumb :items="['系统管理', '角色管理']"/>
    <div class="content">
      <div class="role">
        <div class="role-list">
          <div class="role-item" v-for="(item, index) in roleList" :key="index" @click="showRoleNode(item)">
            <span class="role-title">{{ item.name }}</span>
            <div class="icon">
              <i class="el-icon-edit" @click.stop="updateRole(item)"></i>
              <i class="el-icon-close" @click.stop="deleteRole(item)"></i>
            </div>
          </div>
        </div>
        <div class="btn">
          <el-button type="plain" icon="el-icon-plus" @click="toAddRole">添加角色</el-button>
        </div>
      </div>
      <div class="tree-list">
        <div v-show="role.name" class="top-sticky">
          当前角色：{{ role.name }}
          （勾选完需点保存按钮提交）
          <el-button type="primary" @click="getCheckedNode">保存</el-button>
        </div>
        <el-tree
          :data="treeList"
          ref="tree"
          show-checkbox
          node-key="id"
          :expand-on-click-node="false"
          :default-expand-all="true"
          :props="defaultProps">
          <span slot-scope="{ node, data }">
            <span>{{ data.title }}</span>
            <span>
              <el-button type="text" size="mini" @click="() => append(data)">添加</el-button>
              <el-button type="text" size="mini" @click="() => update(data)">编辑</el-button>
              <el-button type="text" size="mini" @click="() => remove(data)">删除</el-button>
            </span>
          </span>
        </el-tree>
      </div>
    </div>
    <el-dialog :title="isAdd ? '' : ''" :visible.sync="showAdd">
      <el-form :model="nodeForm" label-width="90px" ref="addForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="nodeForm.name"/>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="nodeForm.title"/>
        </el-form-item>
        <el-form-item label="目录级别" prop="level">
          <el-select v-model="nodeForm.level">
            <el-option value="1" label="顶级"/>
            <el-option value="2" label="二级"/>
            <el-option value="3" label="三级"/>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="nodeForm.remark"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="nodeForm.sort"/>
        </el-form-item>
        <el-form-item label="是否展示" prop="isdisplay">
          <el-select v-model="nodeForm.isdisplay">
            <el-option value="1" label="是"/>
            <el-option value="0" label="否"/>
          </el-select>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="nodeForm.icon"/>
        </el-form-item>
        <el-form-item label="前端路由" prop="webrouter">
          <el-input v-model="nodeForm.webrouter"/>
        </el-form-item>
      </el-form>
      <div class="footer" slot="footer">
        <el-button type="primary" @click="toSubmit">提交</el-button>
        <el-button type="danger" @click="showAdd = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'role',
  data () {
    return {
      roleList: [],
      treeList: [],
      defaultProps: {
        children: 'child',
        label: 'title'
      },
      nodeForm: {
        id: '',
        name: '',
        title: '',
        level: '',
        pid: '',
        remark: '',
        sort: '',
        isdisplay: '',
        icon: '',
        webrouter: ''
      },
      isAdd: true,
      showAdd: false,
      addNode: null,
      isChecked: [],
      role: {}
    }
  },
  methods: {
    getRoleList () {
      this.axios.get('/Rbac/role?pid=0')
        .then(res => {
          if (res.data.status === 1) {
            this.roleList = res.data.data.list
          }
        })
    },
    getTreeList () {
      this.axios.get('/Rbac/nodes')
        .then(res => {
          if (res.data.status === 1) {
            let temp = [{
              title: '系统',
              id: 0,
              child: res.data.data
            }]
            this.treeList = temp
          }
        })
    },

    append (data) {
      this.showAdd = true
      this.addNode = data
      this.isAdd = true
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields()
      })
    },
    update (data) {
      this.addNode = data
      this.showAdd = true
      this.isAdd = false
      this.$nextTick(() => {
        Object.keys(this.nodeForm).forEach(key => {
          this.nodeForm[key] = data[key]
        })
      })
    },
    remove (data) {
      this.$confirm('确定删除该权限节点吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/Rbac/delnode', {params: {id: data.id}})
          .then(res => {
            if (res.data.status === 1) {
              this.$message.success(res.data.msg)
              this.getTreeList()
            }
          })
      })
    },

    toSubmit () {
      let url = '/Rbac/addnode'
      if (!this.isAdd) {
        url = '/Rbac/editnode'
      } else {
        this.nodeForm.pid = this.addNode.id
      }
      this.axios.post(url, this.qs.stringify(this.nodeForm))
        .then(res => {
          if (res.data.status === 1) {
            this.$message.success(res.data.msg)
            this.getTreeList()
            this.showAdd = false
          }
        })
    },
    toAddRole () {
      this.$prompt('请输入角色名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        this.axios.post('/Rbac/addRoleHandle', this.qs.stringify({name: value}))
          .then(res => {
            this.$message.success(res.data.msg)
            this.getRoleList()
          })
      })
    },

    updateRole (item) {
      this.$prompt('请输入角色名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.name
      }).then(({ value }) => {
        this.axios.post('/Rbac/setAccess', this.qs.stringify({name: value, rid: item.id}))
          .then(res => {
            this.$message.success(res.data.msg)
            this.getRoleList()
          })
      })
    },
    deleteRole (item) {
      this.$confirm('确定删除该角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/Rbac/delrole', {params: {id: item.id}})
          .then(res => {
            if (res.data.status === 1) {
              this.$message.success(res.data.msg)
              this.getRoleList()
            }
          })
      })
    },

    showRoleNode (item) {
      this.axios.get('/Rbac/access', {params: {id: item.id}})
        .then(res => {
          if (res.data.status === 1) {
            this.role = item
            this.isChecked = this.getArr(res.data.data.list)
            console.log(this.isChecked)
            this.$refs['tree'].setCheckedKeys(this.isChecked)
          }
        })
    },

    getArr (arr) {
      let temp = []
      arr.forEach(item => {
        if (item.access === 1 && !item.child.length) {
          temp.push(item.id)
        }
        if (item.child) {
          temp.push(...(this.getArr(item.child)))
        }
      })
      return temp
    },

    getCheckedNode () {
      let nodes = this.$refs['tree'].getCheckedNodes(false, true)
      let temp = []
      nodes.forEach(node => {
        temp.push(`${node.id}_${node.level}_${node.name}`)
      })
      this.axios.post('/Rbac/setAccess', this.qs.stringify({access: temp, rid: this.role.id}))
        .then(res => {
          this.$message.success(res.data.msg)
          this.getRoleList()
          this.showRoleNode(this.role)
        })
    }
  },
  created () {
    this.getRoleList()
    this.getTreeList()
  }
}
</script>

<style scoped>
  .content{
    display: flex;
    width: 100%;
    align-items: flex-start;
  }
  .role{
    width: 300px;
    flex-grow: 0;
    flex-shrink: 0;
  }
  .tree-list{
    flex-shrink: 1;
    flex-grow: 1;
  }
  .role-list{
    border: 1px solid #DCDFE6;
    border-radius: 8px;
    overflow: hidden;
    margin-right: 10px;
  }
  .role-item{
    height: 40px;
    line-height: 40px;
    padding: 8px;
    position: relative;
    border-bottom: 1px solid #DCDFE6;
    cursor: pointer;
    display: flex;
  }
  .role-item:hover .icon{
    display: inline-block;
  }
  .role-item:last-child{
    border: none;
  }
  .el-tree{
    background-color: #F2F6FC;
    padding-top: 38px;
  }
  .btn{
    text-align: center;
    margin-top: 20px;
  }
  .icon{
    display: none;
    flex-grow: 0;
    flex-shrink: 0;
  }
  .role-title{
    flex-grow: 1;
    flex-shrink: 1;
  }
  .top-sticky{
    position: fixed;
    top: 60px;
    z-index: 100;
    height: 81px;
    display: flex;
    align-items: flex-end;
    background-color: #F2F6FC;
  }
</style>
